package models

import (
	"database/sql"
	"errors"
	"time"
)

// ErrAuthorExists 作者已存在错误
var ErrAuthorExists = errors.New("作者名称已存在")

type Author struct {
	ID        int64  `json:"id"`
	Name      string `json:"name"`
	CreatedAt string `json:"created_at"`
}

// GetAuthorList 获取作者列表，支持分页
func GetAuthorList(db *sql.DB, page, pageSize int) ([]Author, int, error) {
	// 计算偏移量
	offset := (page - 1) * pageSize

	// 获取总数
	var total int
	err := db.QueryRow("SELECT COUNT(*) FROM author").Scan(&total)
	if err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	rows, err := db.Query(
		"SELECT id, book_author, created_at FROM author ORDER BY id DESC LIMIT ? OFFSET ?",
		pageSize,
		offset,
	)
	if err != nil {
		return nil, 0, err
	}
	defer rows.Close()

	var authors []Author
	for rows.Next() {
		var author Author
		err := rows.Scan(&author.ID, &author.Name, &author.CreatedAt)
		if err != nil {
			return nil, 0, err
		}
		authors = append(authors, author)
	}

	return authors, total, nil
}

// CheckAuthorExists 检查作者名称是否已存在
func CheckAuthorExists(db *sql.DB, name string) (bool, error) {
	var count int
	err := db.QueryRow("SELECT COUNT(*) FROM author WHERE book_author = ?", name).Scan(&count)
	if err != nil {
		return false, err
	}
	return count > 0, nil
}

// SearchAuthor 通过作者名搜索作者
func SearchAuthor(db *sql.DB, keyword string) ([]Author, error) {
	// 使用LIKE进行模糊搜索
	rows, err := db.Query(
		"SELECT id, book_author, created_at FROM author WHERE book_author LIKE ? ORDER BY id DESC",
		"%"+keyword+"%",
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var authors []Author
	for rows.Next() {
		var author Author
		err := rows.Scan(&author.ID, &author.Name, &author.CreatedAt)
		if err != nil {
			return nil, err
		}
		authors = append(authors, author)
	}

	return authors, nil
}

// DeleteAuthor 删除作者
func DeleteAuthor(db *sql.DB, id int64) error {
	// 删除作者
	_, err := db.Exec("DELETE FROM author WHERE id = ?", id)
	return err
}

// UpdateAuthor 更新作者信息
func UpdateAuthor(db *sql.DB, id int64, name string) error {
	// 检查新名称是否与其他作者重复
	var existingID int64
	err := db.QueryRow("SELECT id FROM author WHERE book_author = ? AND id != ?", name, id).Scan(&existingID)
	if err == nil {
		return ErrAuthorExists
	} else if err != sql.ErrNoRows {
		return err
	}

	// 更新作者信息
	_, err = db.Exec(
		"UPDATE author SET book_author = ? WHERE id = ?",
		name,
		id,
	)
	return err
}

// CreateAuthor 创建新作者
func CreateAuthor(db *sql.DB, name string) error {
	// 检查作者是否已存在
	exists, err := CheckAuthorExists(db, name)
	if err != nil {
		return err
	}
	if exists {
		return ErrAuthorExists
	}

	// 获取当前时间
	createdAt := time.Now().Format("2006-01-02 15:04:05")

	// 插入数据
	_, err = db.Exec(
		"INSERT INTO author (book_author, created_at) VALUES (?, ?)",
		name,
		createdAt,
	)
	return err
}
